//
//  JSONManagerNSJSONSerializer.swift
//  Pods
//
//  Created by HongPu on 2015/8/4.
//
//

import Foundation

class JSONManagerNSJSONSerializer: JSONManagerProtocol
{
    class func dataToDictionary(data: NSData) -> Result<Dictionary<String, AnyObject>>
    {
        if !NSJSONSerialization.isValidJSONObject(data)
        {
            return .Error(NSError(domain: ERRORDOMINJSONMANAGER, code: -1, reason: "data is not a valid JSONObject"))
        }
        
        var error: NSError?
        let object: AnyObject? = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments, error: &error)
        
        if error**
        {
            return .Error(error!)
        }
        
        if let dict = object as? Dictionary<String, AnyObject>
        {
            return .Success(Box(value: dict))
        }
        
        return .Error(NSError(domain: ERRORDOMINJSONMANAGER, code: -2, reason: "object is not a valid Dictionary<String, AnyObject> objcet"))
    }
}
